package com.miyu.client1.utils.redis;

import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisPassword;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.jedis.JedisClientConfiguration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Component;
import redis.clients.jedis.JedisPoolConfig;

import javax.annotation.PostConstruct;
import java.io.Serializable;
import java.util.*;

//@Component
public class RedisCommon {
    private final static ResourceBundle resourceBundle = ResourceBundle.getBundle("application");


    //服务器地址
    private  final static  String hostName = resourceBundle.getString("spring.redis.host");
    //对应的配置DB
    private  final static  String dbs = resourceBundle.getString("spring.redis.databases");
    //连接端口
    private  final static  int port = Integer.valueOf(resourceBundle.getString("spring.redis.port"));
    //密码
    private  final static  String passWord = resourceBundle.getString("spring.redis.password");


    //连接池最大连接数（使用负值表示没有限制）
    private  final static  int maxActive = Integer.valueOf(resourceBundle.getString("spring.redis.jedis.pool.max-active"));
    //连接池中的最大空闲连接
    private  final static  int maxWait = Integer.valueOf(resourceBundle.getString("spring.redis.jedis.pool.max-wait"));
    //连接池中的最大空闲连接
    private  final static  int maxIdle = Integer.valueOf(resourceBundle.getString("spring.redis.jedis.pool.max-idle"));
    //连接池中的最小空闲连接
    private  final static  int minIdle = Integer.valueOf(resourceBundle.getString("spring.redis.jedis.pool.min-idle"));
    //连接超时时间
    private  final static  int  timeout = Integer.valueOf(resourceBundle.getString("spring.redis.timeout"));
    //是否启用redis
    private  final static  String enable = resourceBundle.getString("spring.redis.enable");

    public static Map<Integer, RedisTemplate<Serializable, Object>> redisTemplateMap = new HashMap<>();
    //初始化db
    private int defaultDb=0;


    public RedisTemplate<Serializable, Object> redisTemplateObject(Integer dbIndex) throws Exception {
        RedisTemplate<Serializable, Object> redisTemplateObject = new RedisTemplate<Serializable, Object>();
        redisTemplateObject.setConnectionFactory(redisConnectionFactory(jedisPoolConfig(), dbIndex));
        setSerializer(redisTemplateObject);
        redisTemplateObject.afterPropertiesSet();
        return redisTemplateObject;
    }


    @PostConstruct
    public void initRedisTemp() throws Exception {
        //判断是否启用redis
        if (!enable.equals("true"))
            return;
         String[] dbps = dbs.split(",");
        System.out.println("###### START 初始化 Redis 连接池 START ######");
        for (String db : dbps) {
            System.out.println("###### 正在加载Redis-db-" + db+ " ######");
            redisTemplateMap.put(Integer.valueOf(db), redisTemplateObject(Integer.valueOf(db)));
        }
        System.out.println("###### END 初始化 Redis 连接池 END ######");
    }


    /**
     * jedis连接工厂
     *
     * @param jedisPoolConfig
     * @return
     */
    public RedisConnectionFactory redisConnectionFactory(JedisPoolConfig jedisPoolConfig, int db) {
        // 单机版jedis
        RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration();
        // 设置redis服务器的host或者ip地址
        redisStandaloneConfiguration.setHostName(hostName);
        // 设置默认使用的数据库
        redisStandaloneConfiguration.setDatabase(db);
        // 设置密码
        redisStandaloneConfiguration.setPassword(RedisPassword.of(passWord));
        // 设置redis的服务的端口号
        redisStandaloneConfiguration.setPort(port);

        // 获得默认的连接池构造器(怎么设计的，为什么不抽象出单独类，供用户使用呢)
        JedisClientConfiguration.JedisPoolingClientConfigurationBuilder jpcb = (JedisClientConfiguration.JedisPoolingClientConfigurationBuilder) JedisClientConfiguration
                .builder();
        // 指定jedisPoolConifig来修改默认的连接池构造器（真麻烦，滥用设计模式！）
        jpcb.poolConfig(jedisPoolConfig);
        // 通过构造器来构造jedis客户端配置
        JedisClientConfiguration jedisClientConfiguration = jpcb.build();
        // 单机配置 + 客户端配置 = jedis连接工厂
        return new JedisConnectionFactory(redisStandaloneConfiguration, jedisClientConfiguration);
    }


    /**
     * 连接池配置信息
     *
     * @return
     */
    public JedisPoolConfig jedisPoolConfig() {
        JedisPoolConfig poolConfig = new JedisPoolConfig();
        // 最大连接数
        poolConfig.setMaxIdle(maxIdle);
        // 最小空闲连接数
        poolConfig.setMinIdle(minIdle);
        poolConfig.setTestOnBorrow(true);
        poolConfig.setTestOnReturn(true);
        poolConfig.setTestWhileIdle(true);
        poolConfig.setNumTestsPerEvictionRun(10);
        poolConfig.setTimeBetweenEvictionRunsMillis(60000);
        // 当池内没有可用的连接时，最大等待时间
        poolConfig.setMaxWaitMillis(10000);
        // ------其他属性根据需要自行添加-------------
        return poolConfig;
    }

    private void setSerializer(RedisTemplate<Serializable, Object> template) {
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
    }


    public RedisTemplate<Serializable, Object> getRedisTemplateByDb(int db){
        return redisTemplateMap.get(db);
    }

    public RedisTemplate<Serializable, Object> getRedisTemplate(){
        return redisTemplateMap.get(defaultDb);
    }


    /**
     * 写入缓存
     * @param key
     * @param value
     * @return
     */
    public boolean set(final String key, Object value,int db) {
        RedisTemplate<Serializable, Object> redisTemplate = getRedisTemplateByDb(db);
        boolean result = false;
        try {
            ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
            operations.set(key, value);
            result = true;
        } catch (Exception e) {

        }
        return result;
    }


}
